package com.mydemo.likedy.controller.UserController;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mydemo.likedy.Service.UserService;
import com.mydemo.likedy.Service.video.TypeService;
import com.mydemo.likedy.Service.video.VideoService;
import com.mydemo.likedy.Utils.JwtUtils;
import com.mydemo.likedy.Utils.Result;
import com.mydemo.likedy.holder.UserHolder;
import com.mydemo.likedy.pojo.entity.video.Type;
import com.mydemo.likedy.pojo.entity.video.Video;
import com.mydemo.likedy.pojo.entity.video.VideoShare;
import com.mydemo.likedy.pojo.vo.BasePage;
import com.mydemo.likedy.properties.UserJwtProperties;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * 视频推送,视频操作
 */
@RestController
@RequestMapping("/luckyjourney/index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private TypeService typeService;

    @Autowired
    UserJwtProperties userJwtProperties;
    /**
     * 兴趣推送视频
     * @return
     */
    @GetMapping("/pushVideos")
    public Result pushVideos(HttpServletRequest request){

        final Long userId = UserHolder.get();
        return Result.success(videoService.pushVideos(userId), UserHolder.get());
    }

    /**
     * 搜索视频
     * @return
     */
    @GetMapping("/search")
    public Result searchVideo(@RequestParam(required = false) String searchName, BasePage basePage, HttpServletRequest request){
        final Long userId = UserHolder.get();
        return Result.success(videoService.searchVideo(searchName,basePage, userId));
    }

    /**
     * 根据视频分类获取
     * @param typeId
     * @return
     */
    @GetMapping("/video/type/{typeId}")
    public Result getVideoByTypeId(@PathVariable Long typeId){
        Collection<Video> videos = videoService.getVideoByTypeId(typeId);
        Integer count=videos.size();

        return Result.success(videos,count);
    }

    /**
     * 获取所有分类
     * @return
     */
    @GetMapping("/types")
    public Result getTypes(HttpServletRequest request){
        final List<Type> types = typeService.list(new LambdaQueryWrapper<Type>().select(Type::getIcon, Type::getId, Type::getName).orderByDesc(Type::getSort));
        final  int count= (int) typeService.count();
        final Set<Long> set = userService.listSubscribeType( UserHolder.get()).stream().map(Type::getId).collect(Collectors.toSet());
        for (Type type : types) {
            if (set.contains(type.getId())) {
                type.setUsed(true);
            }else {
                type.setUsed(false);
            }
        }
        return Result.success(types,count);
    }

    /**
     * 分享视频
     * @param videoId
     * @param request
     * @return
     */
    @PostMapping("/share/{videoId}")
    public Result share(@PathVariable Long videoId, HttpServletRequest request){

        String ip = null;
        if (request.getHeader("x-forwarded-for") == null)
            ip = request.getRemoteAddr();
        else
            ip = request.getHeader("x-forwarded-for");
        final VideoShare videoShare = new VideoShare();

        videoShare.setVideoId(videoId);
        videoShare.setIp(ip);
        videoService.shareVideo(videoShare);
        return Result.success();
    }

    /**
     * 根据id获取视频详情
     * @param id
     * @return
     */
    @GetMapping("/video/{id}")
    public Result getVideoById(@PathVariable Long id,HttpServletRequest request){
        final Long userId =  JwtUtils.getUserId(request,userJwtProperties.getUserSecretKey(),userJwtProperties.getUserTokenName());
        return Result.success(videoService.getVideoById(id,userId));
    }

    /**
     * 获取热度排行榜
     * @return
     */
    @GetMapping("/video/hot/rank")
    public Result listHotRank(){
        return Result.success(videoService.hotRank());
    }

    /**
     * 根据视频标签推送相似视频
     * @param video
     * @return
     */
    @GetMapping("/video/similar")
    public Result pushVideoSimilar(Video video){
        return Result.success(videoService.listSimilarVideo(video));
    }

    /**
     * 推送热门视频
     * @return
     */
    @GetMapping("/video/hot")
    public Result listHotVideo(){
        return Result.success(videoService.listHotVideo());
    }

    /**
     * 根据用户id获取视频
     * @param userId
     * @param basePage
     * @return
     */
    @GetMapping("/video/user")
    public Result listVideoByUserId(@RequestParam(required = false) Long userId,
                               BasePage basePage,HttpServletRequest request){

        userId = userId == null ?  JwtUtils.getUserId(request,userJwtProperties.getUserSecretKey(),userJwtProperties.getUserTokenName()) : userId;
        return Result.success(videoService.listByUserIdOpenVideo(userId,basePage));
    }

    /**
     * 获取用户搜索记录
     * @return
     */
    @GetMapping("/search/history")
    public Result searchHistory(HttpServletRequest request){
        return Result.success(userService.searchHistory( JwtUtils.getUserId(request,userJwtProperties.getUserSecretKey(),userJwtProperties.getUserTokenName())));
    }

    // 删除搜索记录
    @DeleteMapping("/search/history")
    public Result deleteSearchHistory(HttpServletRequest request){
        userService.deleteSearchHistory( JwtUtils.getUserId(request,userJwtProperties.getUserSecretKey(),userJwtProperties.getUserTokenName()));
        return Result.success();
    }
}
